<template>
  <div class="app-container">
    <!--表单组件-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible="crud.status.cu > 0"
      :title="crud.status.title"
      width="800px"
      :top="'10vh'"
    >
      <el-form ref="form" :model="form" size="small" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <div class="tip">
              基础配置
            </div>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="应用名称"
              :rules="[{ required: true, message: '请输入应用名称', trigger: 'blur' }]"
              prop="name"
              style="width: 100%"
            >
              <el-input v-model="form.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="移动端图标"
              prop="appIcon"
              :rules="[{ required: true, message: '请选择移动端图标', trigger: 'blur' }]"
            >
              <el-popover
                placement="bottom-start"
                width="450"
                trigger="click"
                @show="$refs['iconSelect'].reset()"
              >
                <el-button slot="reference" size="small" style="padding: 0px;">
                  <el-image
                    v-if="form.appIcon"
                    :src="form.appIcon"
                    style="height: 32px;width: 32px;"
                  />
                  <i v-else style="font-size: 20px;height: 32px;width: 32px;line-height: 32px" class="el-icon-plus" />
                </el-button>
                <server-image-select ref="iconSelect" :fall-back-function="'selected'" @selected="selected" />
              </el-popover>
              <el-input v-model="form.appIcon" type="hidden" style="width: 200px" placeholder="点击选择图标" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="pc端图标"
              prop="pcIcon"
              :rules="[{ required: true, message: '请选择PC端图标', trigger: 'blur' }]"
            >
              <el-popover
                placement="bottom-start"
                width="450"
                trigger="click"
                @show="$refs['pcselect'].reset()"
              >
                <el-button slot="reference" size="small" style="padding: 0px;">
                  <el-image v-if="form.pcIcon" :src="form.pcIcon" style="height: 32px;width: 32px;" />
                  <i v-else style="font-size: 20px;height: 32px;width: 32px;line-height: 32px" class="el-icon-plus" />
                </el-button>
                <server-image-select ref="pcselect" :fall-back-function="'selectedPc'" @selectedPc="selectedPc" />
              </el-popover>
              <el-input v-model="form.pcIcon" type="hidden" style="width: 200px" placeholder="点击选择图标" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="应用地址"
              :rules="[{ required: true, message: '请输入应用地址', trigger: 'blur' }]"
              prop="openUrl"
            >
              <el-input v-model="form.openUrl" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :rules="[{ required: true, message: '请选择是否权限控制', trigger: 'change' }]"
              label="是否角色授权"
              prop="sfqxkz"
            >
              <el-radio-group v-model="form.sfqxkz">
                <el-radio
                  v-for="item in dict.whether_type"
                  :key="item.id"
                  :label="item.value"
                >{{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :rules="[{ required: true, message: '请选择是否启用', trigger: 'change' }]"
              label="是否启用"
              prop="sfqy"
            >
              <el-radio-group v-model="form.sfqy">
                <el-radio
                  v-for="item in dict.user_status"
                  :key="item.id"
                  :label="item.value"
                >{{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="px">
              <el-input-number
                v-model.number="form.px"
                :min="0"
                :max="999"
                controls-position="right"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="展示对象"
              prop="fwdx"
            >
              <el-checkbox-group v-model="fwdx" size="small">
                <el-checkbox v-for="item in dict.service_dx" :key="item.id" :border="true" :label="item.value">{{
                  item.label
                }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="展现平台"
              prop="zxpt"
            >
              <el-checkbox-group v-model="zxpt" size="small">
                <el-checkbox v-for="item in dict.platform_type" :key="item.id" :border="true" :label="item.value">
                  {{ item.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              :rules="[{ required: true, message: '请选择是否启用', trigger: 'change' }]"
              label="Webhook"
              prop="webhook"
            >
              <el-radio-group v-model="form.webhook">
                <el-radio
                  v-for="item in state"
                  :key="item.id"
                  :label="item.value"
                >{{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <div v-if="form.webhook">
            <el-col :span="24">
              <div class="tip">
                WebHook配置客户端配置<span style="color: red">消息格式：{ type:xx ,data: [...]}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="客户端密钥"
                prop="clientToken"
              >
                <el-input v-model="form.clientToken" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="消息类型"
                prop="xxlx"
              >
                <el-radio-group v-model="form.xxlx" @change="changeXXlx">
                  <el-radio
                    v-for="item in xxlx"
                    :key="item.id"
                    :label="item.value"
                  >{{ item.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <div v-if="form.xxlx === 'notice'">
              <el-col :span="12">
                <el-form-item
                  label="ID参数"
                  prop="oldId"
                  style="width: 100%"
                >
                  <el-input v-model="jxx.oldId" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="标题参数"
                  prop="title"
                  style="width: 100%"
                >
                  <el-input v-model="jxx.title" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="地址参数"
                  prop="title"
                  style="width: 100%"
                >
                  <el-input v-model="jxx.url" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="时间参数"
                  prop="fbsj"
                  style="width: 100%"
                >
                  <el-input v-model="jxx.fbsj" />
                </el-form-item>
              </el-col>
            </div>
            <div v-else>
              <el-col :span="12">
                <el-form-item
                  label="ID参数"
                  prop="oldId"
                  style="width: 100%"
                >
                  <el-input v-model="jxx.oldId" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="标题参数"
                  prop="title"
                  style="width: 100%"
                >
                  <el-input v-model="jxx.title" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="地址参数"
                  prop="title"
                  style="width: 100%"
                >
                  <el-input v-model="jxx.url" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="申请人参数"
                  prop="sqr"
                  style="width: 100%"
                >
                  <el-input v-model="jxx.sqr" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="申请人工号"
                  prop="sqrgh"
                  style="width: 100%"
                >
                  <el-input v-model="jxx.sqrgh" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="办理人工号"
                  prop="userid"
                  style="width: 100%"
                >
                  <el-input v-model="jxx.userid" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="办理人姓名"
                  prop="blrxm"
                  style="width: 100%"
                >
                  <el-input v-model="jxx.blrxm" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="处理时间"
                  prop="times"
                  style="width: 100%"
                >
                  <el-input v-model="jxx.times" />
                </el-form-item>
              </el-col>
            </div>
            <el-col :span="24">
              <div class="tip">
                WebHook服务端配置
              </div>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="调用地址"
                prop="apiUrl"
              >
                <el-input v-model="form.apiUrl" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="密钥"
                prop="serviceToken"
              >
                <el-input v-model="form.serviceToken" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="数据格式"
                prop="sjlx"
              >
                <el-radio-group v-model="form.sjlx">
                  <el-radio
                    v-for="item in sjgs"
                    :key="item.id"
                    :label="item.value"
                  >{{ item.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="推送消息"
                prop="msgType"
              >
                <el-checkbox-group v-model="msgType" size="small">
                  <el-checkbox v-for="item in xxlx" :key="item.id" :border="true" :label="item.value">{{
                    item.label
                  }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </div>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
      </div>
    </el-dialog>
    <el-row :gutter="10">
      <el-col :xs="24" :sm="12" :md="15" :lg="15" :xl="15" style="margin-bottom: 10px">
        <el-card class="box-card">
          <!--工具栏-->
          <div class="head-container">
            <div v-if="crud.props.searchToggle">
              <!-- 搜索 -->
              <el-input
                v-model="query.blurry"
                clearable
                size="small"
                placeholder="输入名称或者描述搜索"
                style="width: 200px;"
                class="filter-item"
                @keyup.enter.native="crud.toQuery"
              />
              <rrOperation />
            </div>
            <crudOperation :permission="permission" />
          </div>
          <!--表格渲染-->
          <el-table
            ref="table"
            v-loading="crud.loading"
            :data="crud.data"
            highlight-current-row
            style="width: 100%;"
            @selection-change="crud.selectionChangeHandler"
            @current-change="handleCurrentChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column :show-overflow-tooltip="true" prop="name" label="名称" />
            <el-table-column :show-overflow-tooltip="true" prop="pcIcon" label="PC端图标">
              <template slot-scope="scope">
                <el-image
                  v-if="scope.row.pcIcon"
                  slot="prefix"
                  :src="scope.row.pcIcon"
                  style="height: 32px;width: 32px;"
                />
              </template>
            </el-table-column>
            <!-- <el-table-column :show-overflow-tooltip="true" prop="appIcon" label="移动端图标">
              <template slot-scope="scope">
                <el-image
                  v-if="scope.row.appIcon"
                  slot="prefix"
                  :src="scope.row.appIcon"
                  style="height: 32px;width: 32px;"
                />
              </template>
            </el-table-column> -->
            <el-table-column :show-overflow-tooltip="true" prop="px" label="排序" />
            <el-table-column label="状态" align="center" prop="sfqy">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.sfqy"
                  :disabled="user.id === scope.row.id"
                  active-color="#409EFF"
                  inactive-color="#F56C6C"
                  @change="changeEnabled(scope.row, scope.row.sfqy)"
                />
              </template>
            </el-table-column>
            <el-table-column
              v-permission="['admin','service:edit','service:del']"
              label="操作"
              width="130px"
              align="center"
              fixed="right"
            >
              <template slot-scope="scope">
                <udOperation
                  :data="scope.row"
                  :permission="permission"
                />
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <pagination />
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="9" :lg="9" :xl="9">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>授权角色</span>
          </div>
          <el-button
            v-if="checkPermission(['admin','application:add']) && this.$refs.roleService && this.$refs.roleService.query.applicationId"
            class="filter-item"
            size="mini"
            style="float: right;padding: 4px 10px"
            type="primary"
            icon="el-icon-plus"
            @click="$refs.roleService && $refs.roleService.crud.toAdd()"
          >新增
          </el-button>
          <role-service ref="roleService" :permission="permission" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import { getToken } from '@/utils/auth'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { mapGetters } from 'vuex'
import serviceManager from '@/api/system/applicationManager'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { queryEnable } from '@/api/system/usystem'
import RoleService from '@/views/system/application/roleService'
import checkPermission from '@/utils/permission'
import ServerImageSelect from '@/components/ServerImageSelect/index'
const defaultForm = {
  id: null, name: null, fwdx: null, zxpt: null, ybsjy: null, px: 0, sfqy: 'true', sfqxkz: 'false',
  openUrl: null, pcIcon: null, appIcon: null, clientId: '', clientToken: '', xxlx: 'db', jxx: '', apiUrl: '',
  serviceToken: '', sjlx: '', msgType: '', webhook: false

}
export default {
  name: 'ManagerServiceIndex',
  components: {
    ServerImageSelect,
    RoleService,
    crudOperation,
    rrOperation,
    udOperation,
    pagination
  },
  cruds() {
    return CRUD({ title: '应用管理', url: 'rest/api/manager/application', crudMethod: { ...serviceManager }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  // 数据字典
  dicts: ['user_status', 'whether_type', 'service_dx', 'platform_type'],
  data() {
    return {
      pc: 'true',
      permission: {
        add: ['admin', 'application:add'],
        edit: ['admin', 'application:edit'],
        del: ['admin', 'application:del']
      },
      fwdx: [],
      zxpt: [],
      msgType: [],
      xxlx: [
        { id: 0, value: 'db', label: '待办消息' },
        { id: 1, value: 'notice', label: '消息公告' }
      ],
      state: [
        { id: 0, value: false, label: '否' },
        { id: 1, value: true, label: '是' }
      ],
      sjgs: [
        { id: 0, value: 'JSON', label: 'json' },
        { id: 1, value: 'XML', label: 'xml' }
      ],
      jxx: {},
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      baseURL: process.env.NODE_ENV === 'production' ? process.env.VUE_APP_BASE_API : '/', // api 的 base_url
      customHeader: { 'APEXEDU': getToken() }
    }
  },
  created() {
    queryEnable().then(res => {
      this.systems = res
    }).catch(error => {
      console.log('error:' + error)
    })
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  methods: {
    checkPermission,
    [CRUD.HOOK.afterAddError](crud) {
      this.afterErrorMethod(crud)
    },
    [CRUD.HOOK.afterEditError](crud) {
      this.afterErrorMethod(crud)
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      form.sfqy = form.sfqy.toString()
      form.sfqxkz = form.sfqxkz.toString()
      if (form.fwdx != null && form.fwdx !== '') {
        this.fwdx = form.fwdx.split(',')
      } else {
        this.fwdx = []
      }
      if (form.zxpt !== null && form.zxpt !== '') {
        this.zxpt = form.zxpt.split(',')
      } else {
        this.zxpt = []
      }
      if (form.jxx !== null && form.jxx !== '') {
        this.jxx = JSON.parse(form.jxx)
      } else {
        this.jxx = {}
      }
      if (form.msgType !== null && form.msgType !== '') {
        this.msgType = form.msgType.split(',')
      } else {
        this.msgType = []
      }
    },
    // 改变状态
    changeEnabled(data, val) {
      this.$confirm('此操作将 "' + this.dict.label.user_status[val] + '" ' + data.name + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        serviceManager.edit(data).then(res => {
          this.crud.notify(this.dict.label.user_status[val] + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(() => {
          data.enabled = !data.enabled
        })
      }).catch(() => {
        data.enabled = !data.enabled
      })
    },
    changeXXlx() {
      this.jxx = {}
    },
    selected(name) {
      this.form.appIcon = name.url
    },
    selectedPc(name) {
      this.form.pcIcon = name.url
    },
    // 选中字典后，设置字典详情数据
    handleCurrentChange(val) {
      if (val) {
        this.$refs.roleService.applicationId = val.id
        this.$refs.roleService.query.applicationId = val.id
        this.$refs.roleService.crud.toQuery()
      }
    },
    callBack(data) {}
  },
  watch: {
    fwdx: {
      handler(newName, oldName) { // 值发生变化时
        this.form.fwdx = newName.toString()
      },
      immediate: true, // 父组件第一次传值时，执行handler，false则第一次不执行
      deep: true // formType为对象时，设置为true，此属性监听对象发生变化
    },
    msgType: {
      handler(newName, oldName) { // 值发生变化时
        this.form.msgType = newName.toString()
      },
      immediate: true, // 父组件第一次传值时，执行handler，false则第一次不执行
      deep: true // formType为对象时，设置为true，此属性监听对象发生变化
    },
    zxpt: {
      handler(newName, oldName) { // 值发生变化时
        this.form.zxpt = newName.toString()
      },
      immediate: true, // 父组件第一次传值时，执行handler，false则第一次不执行
      deep: true // formType为对象时，设置为true，此属性监听对象发生变化
    },
    jxx: {
      handler(newName, oldName) { // 值发生变化时
        this.form.jxx = JSON.stringify(newName)
      },
      immediate: true, // 父组件第一次传值时，执行handler，false则第一次不执行
      deep: true // formType为对象时，设置为true，此属性监听对象发生变化
    }
  }
}
</script>

<style scoped>
.tip {
  padding: 8px 16px;
  background-color: #ecf8ff;
  border-radius: 4px;
  border-left: 5px solid #50bfff;
  margin: 20px 0;
}
</style>
